<template>
	<view class="container">
		<uni-forms ref="form" :model="formData" :rules="rules" label-position="top">
			<!-- 商品名称 -->
			<uni-forms-item label="商品名称" name="name" required>
				<uni-easyinput v-model="formData.name" placeholder="请输入商品名称" />
			</uni-forms-item>
			
			<!-- 商品类型 -->
			<uni-forms-item label="商品类型" name="categoryId" required>
				<view class="category-selector">
					<uni-data-picker 
						v-model="formData.categoryId" 
						:localdata="categoryOptions" 
						popup-title="选择商品类型"
						@change="handleCategoryChange"
					></uni-data-picker>
				</view>
				<view class="category-path" v-if="formData.categoryPath">
					<text>当前选择: {{formData.categoryPath}}</text>
				</view>
			</uni-forms-item>
			
			<!-- 商品图片 -->
			<uni-forms-item label="商品图片" name="images" required>
				<uni-file-picker 
					v-model="formData.images" 
					file-mediatype="image" 
					mode="grid" 
					limit="6" 
					@select="selectImages" 
					@delete="deleteImage"
				></uni-file-picker>
			</uni-forms-item>
			
			<!-- 商品价格 -->
			<uni-forms-item label="商品价格(元)" name="price" required>
				<uni-easyinput v-model="formData.price" type="number" placeholder="请输入商品价格" />
			</uni-forms-item>
			
			<!-- 价格区间 -->
			<view class="price-range">
				<uni-forms-item label="最低价格(元)" name="minPrice">
					<uni-easyinput v-model="formData.minPrice" type="number" placeholder="请输入最低价格" />
				</uni-forms-item>
				
				<uni-forms-item label="最高价格(元)" name="maxPrice">
					<uni-easyinput v-model="formData.maxPrice" type="number" placeholder="请输入最高价格" />
				</uni-forms-item>
			</view>
			
			<!-- 一口价 -->
			<uni-forms-item label="一口价(元)" name="fixedPrice">
				<uni-easyinput v-model="formData.fixedPrice" type="number" placeholder="请输入一口价" />
			</uni-forms-item>
			
			<!-- 所属人 -->
			<uni-forms-item label="所属人" name="owner">
				<uni-easyinput v-model="formData.owner" placeholder="请输入所属人" />
			</uni-forms-item>
			
			<!-- 空闲时间 -->
			<uni-forms-item label="空闲时间" name="availableTime">
				<uni-easyinput v-model="formData.availableTime" placeholder="请输入空闲时间，如：周一至周五 9:00-18:00" />
			</uni-forms-item>
			
			<!-- 商品状态 -->
			<uni-forms-item label="商品状态" name="status" required>
				<uni-data-checkbox 
					v-model="formData.status" 
					:localdata="statusOptions" 
					mode="tag" 
				></uni-data-checkbox>
			</uni-forms-item>
			
			<!-- 上下架状态 -->
			<uni-forms-item label="上架状态" name="isOnShelf" required>
				<uni-data-checkbox 
					v-model="formData.isOnShelf" 
					:localdata="shelfOptions" 
					mode="tag" 
				></uni-data-checkbox>
			</uni-forms-item>
			
			<!-- 商品描述 -->
			<uni-forms-item label="商品描述" name="description">
				<uni-easyinput v-model="formData.description" type="textarea" placeholder="请输入商品描述" />
			</uni-forms-item>
			
			<!-- 提交按钮 -->
			<view class="form-actions">
				<button class="submit-btn" @click="submitForm">保存</button>
				<button class="cancel-btn" @click="goBack">取消</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import { getProductCategories, addProduct, updateProduct } from '@/api/pet/product.js';
	
	export default {
		data() {
			return {
				isEdit: false,
				productId: '',
				formData: {
					name: '',
					categoryId: '',
					categoryPath: '',
					images: [],
					price: '',
					minPrice: '',
					maxPrice: '',
					fixedPrice: '',
					owner: '',
					availableTime: '',
					status: '1',
					isOnShelf: '1',
					description: ''
				},
				rules: {
					name: {
						rules: [
							{ required: true, errorMessage: '请输入商品名称' }
						]
					},
					categoryId: {
						rules: [
							{ required: true, errorMessage: '请选择商品类型' }
						]
					},
					images: {
						rules: [
							{ required: true, errorMessage: '请上传至少一张商品图片' }
						]
					},
					price: {
						rules: [
							{ required: true, errorMessage: '请输入商品价格' }
						]
					},
					status: {
						rules: [
							{ required: true, errorMessage: '请选择商品状态' }
						]
					},
					isOnShelf: {
						rules: [
							{ required: true, errorMessage: '请选择上架状态' }
						]
					}
				},
				categoryOptions: [],
				statusOptions: [
					{ value: '1', text: '出售中' },
					{ value: '2', text: '已售出' },
					{ value: '3', text: '已取消' },
					{ value: '4', text: '锁定中' }
				],
				shelfOptions: [
					{ value: '1', text: '上架' },
					{ value: '0', text: '下架' }
				]
			}
		},
		onLoad(options) {
			if (options.id) {
				this.isEdit = true;
				this.productId = options.id;
				this.loadProductDetail();
			}
			
			this.loadCategories();
		},
		methods: {
			async loadCategories() {
				try {
					const res = await getProductCategories();
					if (res.code === 200) {
						this.formatCategoryData(res.data);
					}
				} catch (error) {
					console.error('Failed to load categories:', error);
					uni.showToast({
						title: '加载商品类型失败',
						icon: 'none'
					});
				}
			},
			formatCategoryData(data) {
				// 将扁平数据转换为树形结构
				this.categoryOptions = this.convertToTree(data);
			},
			convertToTree(data) {
				// 示例转换方法，实际实现可能需要根据后端数据结构调整
				const result = [];
				const map = {};
				
				// 先创建所有节点的映射
				data.forEach(item => {
					map[item.id] = {
						...item,
						text: item.name,
						value: item.id,
						children: []
					};
				});
				
				// 构建树形结构
				data.forEach(item => {
					const node = map[item.id];
					if (item.parentId && map[item.parentId]) {
						map[item.parentId].children.push(node);
					} else {
						result.push(node);
					}
				});
				
				return result;
			},
			async loadProductDetail() {
				try {
					const res = await getProductDetail(this.productId);
					if (res.code === 200) {
						const product = res.data;
						
						// 填充表单数据
						this.formData = {
							name: product.name,
							categoryId: product.categoryId,
							categoryPath: product.categoryPath,
							images: product.images ? product.images.map(url => ({ url })) : [],
							price: product.price,
							minPrice: product.minPrice,
							maxPrice: product.maxPrice,
							fixedPrice: product.fixedPrice,
							owner: product.owner,
							availableTime: product.availableTime,
							status: String(product.status),
							isOnShelf: product.isOnShelf ? '1' : '0',
							description: product.description
						};
					}
				} catch (error) {
					console.error('Failed to load product detail:', error);
					uni.showToast({
						title: '加载商品详情失败',
						icon: 'none'
					});
				}
			},
			handleCategoryChange(e) {
				const selectedItem = e.detail.data[e.detail.data.length - 1];
				if (selectedItem) {
					// 构建类别路径
					const path = e.detail.data.map(item => item.text).join(' > ');
					this.formData.categoryPath = path;
				}
			},
			selectImages(e) {
				// 处理图片选择
				console.log('Selected images:', e.tempFilePaths);
				// 实际项目中，这里可能需要先上传图片到服务器，然后获取URL
			},
			deleteImage(e) {
				// 处理图片删除
				console.log('Deleted image:', e);
			},
			async submitForm() {
				this.$refs.form.validate().then(async (res) => {
					if (res) {
						try {
							// 准备提交的数据
							const submitData = {
								...this.formData,
								isOnShelf: this.formData.isOnShelf === '1',
								status: Number(this.formData.status),
								// 如果images是对象数组，需要提取URL
								images: this.formData.images.map(img => typeof img === 'string' ? img : img.url)
							};
							
							let res;
							if (this.isEdit) {
								submitData.id = this.productId;
								res = await updateProduct(submitData);
							} else {
								res = await addProduct(submitData);
							}
							
							if (res.code === 200) {
								uni.showToast({
									title: this.isEdit ? '更新成功' : '添加成功',
									icon: 'success'
								});
								
								setTimeout(() => {
									this.goBack();
								}, 1500);
							}
						} catch (error) {
							console.error('Failed to submit form:', error);
							uni.showToast({
								title: '提交失败',
								icon: 'none'
							});
						}
					}
				}).catch(err => {
					console.log('表单验证失败:', err);
				});
			},
			goBack() {
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss">
.container {
	padding: 30rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
	
	.uni-forms {
		background-color: #FFFFFF;
		border-radius: 12rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.price-range {
		display: flex;
		justify-content: space-between;
		
		.uni-forms-item {
			width: 48%;
		}
	}
	
	.category-path {
		margin-top: 10rpx;
		font-size: 26rpx;
		color: #666;
	}
	
	.form-actions {
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;
		
		button {
			width: 45%;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			font-size: 30rpx;
		}
		
		.submit-btn {
			background-color: #007AFF;
			color: #FFFFFF;
		}
		
		.cancel-btn {
			background-color: #F2F2F2;
			color: #333333;
		}
	}
}
</style>